package com.qf.controller;

import com.qf.dto.ApiResult;
import com.qf.entity.response.IndexResponse;
import com.qf.service.IOrderService;
import com.qf.service.IUserService;
import com.qf.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: chen
 * @Date: 2021/3/26 4:32 PM
 * @Version 1.0
 */
@RestController
@RequestMapping("/index")
@Api(tags = "后台首页相关接口")
public class IndexController {

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IUserService userService;

    @PostMapping("/index")
    @ApiOperation("首页数据统计")
    @CrossOrigin
    public ApiResult getData() throws ParseException {

        IndexResponse indexResponse = new IndexResponse();
        //销售额
        indexResponse.setTotalSales( orderService.selectSumToBuy(null,null));

        //总用户数
        indexResponse.setTotalUser(userService.count());

        indexResponse.setOrderGoods(orderService.getOrderSum(0));
        indexResponse.setNotOrderGoods(orderService.getOrderSum(1));

        List<String> timeSales = new ArrayList<>();
        List<BigDecimal> weekSales = new ArrayList<>();
        for(int i=6;i>=0;i--){
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
                    "yyyy-MM-dd");
            String format = simpleDateFormat.format(DateUtils.addDays(new Date(), -i));
            timeSales.add(format);

            //当天的00：00：00 【开始时间】
            Date parse = simpleDateFormat.parse(format);
            //结束时间
            Date date = DateUtils.addSeconds(DateUtils.addMinutes(
                    DateUtils.addHours(parse, 23), 59), 59);
            BigDecimal bigDecimal = orderService.selectSumToBuy(parse, date);
            weekSales.add(bigDecimal);
        }
        indexResponse.setTimeSales(timeSales);
        indexResponse.setWeekSales(weekSales);

        return R.ok(indexResponse);
    }

}
